package com.sh;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class UdpServer {
    public static void main(String[] args) {
        System.out.println("服务端启动，监听端口 10010");

        // 创建并绑定一个 UDP 套接字到端口 10010
        try (DatagramSocket socket = new DatagramSocket(10010)) {
            while (true) {
                // 用于接收数据的字节数组
                byte[] buffer = new byte[1024];

                // 创建数据包用于接收数据
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                // 接收数据包（阻塞调用）
                socket.receive(packet);

                // 从数据包中提取数据
                String receivedMessage = new String(packet.getData(), 0, packet.getLength());

                System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) +"收到消息: " + receivedMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
